import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

public class WirelessDevice implements DiscoveryListener {

	//object used for waiting
    private static Object lock=new Object();
    
    private static RemoteDevice NXTDevice = null;
    
    LocalDevice localDevice = null;
    private static String connectionURL; //="btspp://001653086C15:1;authenticate=false;encrypt=false;master=false";
    //private static final String CHARSET = "UTF-8";

    //main method of the application
    public WirelessDevice() throws Exception {
        
        
        //display local device address and name
        LocalDevice localDevice = LocalDevice.getLocalDevice();
        System.out.println("Address: "+localDevice.getBluetoothAddress());
        System.out.println("Name: "+localDevice.getFriendlyName());
        
        //find devices
        DiscoveryAgent agent = localDevice.getDiscoveryAgent();
      
        System.out.println("Starting device inquiry...");
        agent.startInquiry(DiscoveryAgent.GIAC, this);
        
        try {
            synchronized(lock){
                lock.wait();
            }
        } 
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        
        System.out.println("Device Inquiry Completed. ");
        
        //print all devices in vecDevices
        if(NXTDevice == null){
            System.out.println("No Device Found .");
        }
        else{
            //print bluetooth device addresses and names in the format [ No. address (name) ]
            System.out.println("NXTBluetooth Device: ");
            System.out.println(NXTDevice.getBluetoothAddress());
        }
        
        connectionURL = agent.selectService(new UUID("1101",true),0,false);
        System.out.println(connectionURL);
        StreamConnection c = (StreamConnection) Connector.open(connectionURL);
        System.out.println("Connection established..");
        DataInputStream dis = c.openDataInputStream();
        DataOutputStream dos = c.openDataOutputStream();
       
        Thread.sleep(2000);
        
        String a = "Hello";
       String b = " World";
        byte[] sendMsg = a.getBytes("UTF-8");
        byte[] sendMsg2 = b.getBytes("UTF-8");
        dos.write(sendMsg);
        
        dos.write(sendMsg2);
//        System.out.println(sendMsg.length);
//        StringBuffer buffer1 = new StringBuffer();
//		for(int i = 0; i<sendMsg.length; i++){
//		Byte mybyte = new Byte(sendMsg[i]);
//		buffer1.append(mybyte.byteValue());
//		}
//		System.out.println(buffer1.);
        
        Thread.sleep(1000);
        
        dis.close();
        dos.close();
        Thread.sleep(100);
        c.close();
        
    }
    //methods of DiscoveryListener
    
    /**
     * This call back method will be called for each discovered bluetooth devices.
     */
    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
        System.out.println("Device discovered: "+btDevice.getBluetoothAddress());
        //add the device to the vector
        try {
			if(btDevice.getFriendlyName(true).equals("NXT")){
				NXTDevice = btDevice;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
 
    /**
     * Called when a bluetooth service is discovered.
     * Used for service search.
     */
    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
        if(servRecord!=null && servRecord.length>0){
            connectionURL=servRecord[0].getConnectionURL(0,false);
        }
        synchronized(lock){
            lock.notify();
        }
    }
 
    
    /**
     * Called when the service search is over.
     */
    public void serviceSearchCompleted(int transID, int respCode) {
        synchronized(lock){
            lock.notify();
        }
    }

 
    
    /**
     * This callback method will be called when the device discovery is 
     * completed.
     */
    public void inquiryCompleted(int discType) {
        synchronized(lock){
            lock.notify();
        }
        
        switch (discType) {
            case DiscoveryListener.INQUIRY_COMPLETED :
                System.out.println("INQUIRY_COMPLETED");
                break;
                
            case DiscoveryListener.INQUIRY_TERMINATED :
                System.out.println("INQUIRY_TERMINATED");
                break;
                
            case DiscoveryListener.INQUIRY_ERROR :
                System.out.println("INQUIRY_ERROR");
                break;
 
            default :
                System.out.println("Unknown Response Code");
                break;
        }
    }
}
